<?php

/**
 * @Author: Wang Chunsheng 2192138785@qq.com
 * @Date:   2020-03-01 18:26:13
 * @Last Modified by:   Wang Chunsheng 2192138785@qq.com
 * @Last Modified time: 2020-03-14 16:43:35
 */

namespace app\modules\diandi_shop\controllers\goods;


use Yii;

use app\modules\diandi_shop\models\DdGoods;
use app\modules\diandi_shop\models\DdGoodsSearch;
use backend\controllers\BaseController;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\data\ActiveDataProvider;
use yii\web\Response;
use common\widgets\MyActiveForm;
use app\modules\diandi_shop\models\DdSpec;
use common\components\MyStringHelp;
use common\helpers\LevelTplHelper;
use app\modules\diandi_shop\models\DdGoodsSpec;
use app\modules\diandi_shop\models\DdGoodsSpecRel;
use app\modules\diandi_shop\models\DdSpecValue;
use app\modules\diandi_shop\models\DdCategory;
use app\modules\diandi_shop\models\DdGoodsParam;
use common\helpers\ErrorsHelper;
use common\helpers\ImageHelper;
use manks\FileInput;
use yii\base\InvalidCallException;
use yii\db\Transaction;
use yii\web\BadRequestHttpException;

/**
 * DdGoodsController implements the CRUD actions for DdGoods model.
 */
class DdGoodsController extends BaseController
{
    public function actions()
    {
        return [
            'upload' => [
                'class' => 'kucha\ueditor\UEditorAction',
                'config' => [
                    "imageUrlPrefix" => "http://www.cc.com", //图片访问路径前缀
                    "imagePathFormat" => "/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}" //上传保存路径
                ],
            ]
        ];
    }
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all DdGoods models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new DdGoodsSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single DdGoods model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     *
     */
    public function actionAdds()
    {
        $data = Yii::$app->request->post();
        $model = new DdGoods();

        /* 基础信息 */
        $base = $data['DdGoods'];
        $goods_base['DdGoods'] = [
            'goods_name' => $base['goods_name'],
            'category_id' => $base['category_id'],
            'category_pid' => $base['category_pid'],
            'spec_type' => $base['spec_type'],
            'deduct_stock_type' => $base['deduct_stock_type'],
            'content' => $base['content'],
            'sales_initial' => $base['sales_initial'],
            'sales_actual' => $base['sales_actual'],
            'goods_sort' => $base['goods_sort'],
            'delivery_id' => $base['delivery_id'],
            'goods_status' => $base['goods_status'],
            'thumb' => $base['thumb'],
            'is_delete' => $base['is_delete'],
            'images' => serialize($base['images']),
            'line_price' => $base['line_price'],
            'goods_price' => $base['goods_price'],
            'stock' => $base['stock'],

            // 'wxapp_id' => 'Wxapp ID',
            // 'create_time' => 'Create Time',
            // 'update_time' => 'Update Time',
            // 'spec_item_thumb' => '属性图片'
        ];

        if ($model->validate($data)) {
            if ($model->load($goods_base)) {
                $tr = Yii::$app->db->beginTransaction(Transaction::READ_COMMITTED);
                try {
                    if ($model->save()) {
                        $goods_id = Yii::$app->db->getLastInsertID();
                        $model->saveSpec($goods_id, $data);
                        $tr->commit();
                    } else {
                        $message = ErrorsHelper::getModelError($model);

                        throw new BadRequestHttpException($message);
                    }
                } catch (\Exception $e) {
                    $tr->rollBack();
                    throw $e;
                }
                return $this->redirect(['view', 'id' => $goods_id]);
            }
        }
    }

    //该方法是异步校验字段，输入框失去焦点之后自动会自动请求改地址
    public function actionValidate()
    {
        $model = new DdGoods();
        if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            return MyActiveForm::validate($model);
        }
    }



    /**
     * Creates a new DdGoods model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new DdGoods();
        $modelcate = new DdCategory();
        $Helper = new LevelTplHelper([
            'pid' => 'parent_id',
            'cid' => 'category_id',
            'title' => 'name',
            'model' => $modelcate,
            'id' => 'category_id'
        ]);
        $query = $modelcate::find();
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => false,
        ]);

        $catedata = DdCategory::find()->All();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->goods_id]);
        } else {
            $MyStringHelp = new MyStringHelp(['_string' => Yii::$app->getSecurity()->generateRandomString()]);
            $specitem = [];
            $params = [];
            $html = '';
            $spec = [
                'id' => $MyStringHelp->CreateString('_')
            ];
            $model->goods_status = 1;
            $model->deduct_stock_type = 10;

            return $this->render('create', [
                'model' => $model,
                'catedata' => $catedata,
                'modelcate' => $modelcate,
                'dataProvider' => $dataProvider,
                'Helper' => $Helper,
                'specitem' => $specitem,
                'params' => $params,
                'spec' => $spec,
                'op' => 'create'


            ]);
        }
    }



    /**
     * Updates an existing DdGoods model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if (Yii::$app->request->isPost) {
            $data = Yii::$app->request->post();
            /* 基础信息 */
            $base = $data['DdGoods'];
            $goods_base['DdGoods'] = [
                'goods_name' => $base['goods_name'],
                'category_id' => $base['category_id'],
                'category_pid' => $base['category_pid'],
                'spec_type' => $base['spec_type'],
                'deduct_stock_type' => $base['deduct_stock_type'],
                'content' => $base['content'],
                'sales_initial' => $base['sales_initial'],
                'sales_actual' => $base['sales_actual'],
                'goods_sort' => $base['goods_sort'],
                'delivery_id' => $base['delivery_id'],
                'goods_status' => $base['goods_status'],
                'is_delete' => $base['is_delete'],
                'thumb' => $base['thumb'],
                'images' => serialize($base['images']),
                'line_price' => $base['line_price'],
                'goods_price' => $base['goods_price'],
                'stock' => $base['stock'],
                // 'wxapp_id' => 'Wxapp ID',
                // 'create_time' => 'Create Time',
                // 'update_time' => 'Update Time',
                // 'spec_item_thumb' => '属性图片'
            ];


            if ($model->load($goods_base) && $model->save()) {
                $model->saveSpec($model->goods_id, $data);

                return $this->redirect(['view', 'id' => $model->goods_id]);
            } else {
                $message = ErrorsHelper::getModelError($model);

                throw new BadRequestHttpException($message);
            }
        } else {
            $model->images = unserialize($model->images);
            $modelcate = new DdCategory();
            $Helper = new LevelTplHelper([
                'pid' => 'parent_id',
                'cid' => 'category_id',
                'title' => 'name',
                'model' => $modelcate,
                'id' => 'category_id'
            ]);
            $query = $modelcate::find();
            $dataProvider = new ActiveDataProvider([
                'query' => $query,
                'pagination' => false,
            ]);
            $catedata = $modelcate::find()->All();
            $modelcate->category_pid = $model->category_pid;

            $MyStringHelp = new MyStringHelp(['_string' => Yii::$app->getSecurity()->generateRandomString()]);
            $specitem = [];
            $params = DdGoodsParam::findAll(['goods_id' => $id]);
            $html = '';
            $spec = [
                'id' => $MyStringHelp->CreateString('_')
            ];

            // $ss = DdGoodsSpec::find()->where(['goods_id'=>$goods_id])->with('specvalue');

            $specitems = DdGoodsSpecRel::find()->where(['goods_id' => $id])->with('specvalue')->asarray()->all();

            $specv = [];
            if (!empty($specitems)) {
                foreach ($specitems as $key => $value) {
                    $model->spec_item_thumb[$value['spec_id']][$value['spec_value_id']] = $value['thumb'];
                    $spec_item_thumbs[$value['spec_id']][$value['spec_value_id']]['spec_item_thumb'] = $value['thumb'];
                    $spec_item_shows[$value['spec_id']][$value['spec_value_id']]['spec_item_show']  = $value['spec_item_show'];
                    // $model->spec_item_thumb = $value['thumb'];

                    $specs[$value['spec_id']] = $value['spec_id'];
                    $specitem[$value['spec_id']][$value['specvalue']['spec_value_id']] = $value['specvalue']['spec_value'];
                }
                $specv = DdSpec::find()
                    ->where(['in', 'spec_id', $specs])
                    ->select('spec_name,spec_id')
                    ->indexBy('spec_id')
                    ->asArray()
                    ->all();
            }
            $allspecs = DdGoodsSpec::find()->where(['goods_id' => $id])->with('goodsSpecRel')->asArray()->all();
            $DdGoodsSpecRel = new DdGoodsSpecRel();
            $html = $DdGoodsSpecRel->buildHtml($id);

            return $this->render('update', [
                'model' => $model,
                'catedata' => $catedata,
                'modelcate' => $modelcate,
                'dataProvider' => $dataProvider,
                'Helper' => $Helper,
                'specitem' => $specitem,
                'params' => $params,
                'spec' => $spec,
                'spec_item_shows' => $spec_item_shows,
                'spec_item_thumbs' => $spec_item_thumbs,
                'html' => $html,
                'op' => 'update',
                'specv' => $specv
            ]);
        }
    }

    /**
     * Deletes an existing DdGoods model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }


    /**
     * 添加规格页面.
     *
     * @param int|null post
     * @return string
     * @throws NotFoundHttpException
     */
    public function actionSpecitem()
    {
        if (Yii::$app->request->isAjax) {
            // Yii::$app->response->format = Response::FORMAT_JSON;
            $data = Yii::$app->request->post();
            $pids = $data['specid'];

            $title = Yii::$app->request->post('title', '');
            $MyStringHelp = new MyStringHelp(['_string' => Yii::$app->getSecurity()->generateRandomString()]);
            $ids = $MyStringHelp->CreateString('_');

            $specitem = array(
                "ids" => $ids,
                "title" => $title,
                "show" => 1
            );
            $spec = array(
                "ids" => $pids
            );
            $model = new DdGoods();


            $form = MyActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]);

            return $this->renderAjax('spec_item', [
                'specitem' => $specitem,
                'spec' => $spec,
                'model' => $model,
                'form' => $form
            ]);
        }
    }


    public function actionParam()
    {
        $MyStringHelp = new MyStringHelp(['_string' => Yii::$app->getSecurity()->generateRandomString()]);

        $tag = $MyStringHelp->CreateString('_');;
        $model = new DdGoods();

        return $this->renderAjax('param', [
            'tag' => $tag,
            'model' => $model,

        ]);
    }

    /**
     * 添加规格
     *
     * @param int|null post
     * @return string
     * @throws NotFoundHttpException
     */
    public function actionSpec()
    {
        if (Yii::$app->request->isAjax) {
            $data = Yii::$app->request->post();

            $title = Yii::$app->request->post('title', '');
            $MyStringHelp = new MyStringHelp(['_string' => Yii::$app->getSecurity()->generateRandomString()]);

            $ids = $MyStringHelp->CreateString('_');
            if ($data['specid']) {
                $ids = $data['specid'];
            }

            $model = new DdGoods();

            $spec = array(
                "id" => $ids,
                "title" => $title
            );
            return $this->renderPartial('spec', [
                'spec' => $spec,
                'model' => $model,
                'specitem' => []
            ]);
        }
    }

    /**
     * Finds the DdGoods model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return DdGoods the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = DdGoods::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('The requested page does not exist.');
    }
}
